// https://thebookofshaders.com/07/?lan=ch
import { 
  Camera,  
  Color,  
  Mesh, 
  PlaneBufferGeometry, 
  Scene, 
  ShaderMaterial, 
  Vector3, 
  WebGLRenderer 
} from "three"
import stats from '../../utils/stats'

const canvas = document.createElement('canvas')
canvas.style.width = '100vw'
canvas.style.height = '100vh'
canvas.width = window.innerWidth
canvas.height = window.innerHeight
document.body.appendChild(canvas)

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new Camera()
camera.position.z = 1
const plane = new PlaneBufferGeometry(2, 3)

// 片段着色器
const fragmentShader = `
#include <common>

uniform vec2 u_resolution;
uniform float u_time;

float circle(in vec2 _st, in float r) {
  vec2 dist = _st-vec2(0.5);

  return 1.0 - smoothstep(r - (r * 0.01), r+(r * 0.01), dot(dist, dist) * 4.0);
}

void main() {
  vec2 st = gl_FragCoord.xy / u_resolution.xy;

  float r = abs(sin(u_time));
  vec3 color = vec3(circle(st, r));

  gl_FragColor = vec4(color, 1.0);
}
`

const uniforms = {
  u_time: { value: 0 },
  u_resolution: { value: new Vector3() },
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms
})
scene.add(new Mesh(plane, material))

function render(time: number) {
  stats.update()
  // 转化成秒
  time *= 0.001

  uniforms.u_time.value = time
  const canvas = renderer.domElement
  uniforms.u_resolution.value.set(canvas.width, canvas.height, 1)

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)